package com.gitee.simons.admin.config;

import com.gitee.simons.common.utils.DateUtil;
import com.gitee.simons.common.utils.SendMailUtil;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.domain.values.Registration;
import de.codecentric.boot.admin.server.domain.values.StatusInfo;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import reactor.core.publisher.Mono;

import java.util.Date;


/**
 * @author jsm
 * 自定义系统邮件通知
 */
@Slf4j
public class CustomNotifier  extends AbstractEventNotifier {

    /**
     * 标题
     */
    @Value("${info.mail.subject}")
    private String subject;
    /**
     * 请求方式
     */
    @Value("${info.mail.protocol}")
    private String protocol;
    /**
     * 发件箱的地址
     */
    @Value("${info.mail.host}")
    private String host;
    /**
     * 发件箱的端口
     */
    @Value("${info.mail.port}")
    private String port;
    /**
     * 发邮件的用户名
     */
    @Value("${info.mail.userName}")
    private String userName;
    /**
     * 发邮件的密码
     */
    @Value("${info.mail.userPwd}")
    private String userPwd;

    /**
     * 需要发送的人的地址
     */
    @Value("${info.mail.addrs}")
    private String[] addrs;

    public CustomNotifier(InstanceRepository repository) {
        super(repository);
    }

    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        return Mono.fromRunnable(() -> {
            if (event instanceof InstanceStatusChangedEvent) {
                Registration registration = instance.getRegistration();
                String appName = registration.getName();
                String url = registration.getServiceUrl();

                StatusInfo statusInfo = ((InstanceStatusChangedEvent) event).getStatusInfo();
                String toStatus = statusInfo.getStatus();
                String content =
                        "地址为[" + url + "]的服务[" + appName + "]<br>于[" + DateUtil.format(new Date()) + "]<br>服务状态转变为[" + toStatus +
                        "]<br>请相关人员留意服务运行状态";
                log.warn(content);
                SendMailUtil.send(addrs, subject, content, protocol, host, port, userName, userPwd);
                }
        });
    }
}
